package org.popo.web;

import static org.popo.Contans.APP_KEY;
import static org.popo.Contans.APP_SECRET;
import static org.popo.Contans.APP_URL;
import static org.popo.Contans.SESSION_KEY;

import java.util.LinkedList;

import org.debux.webmotion.server.WebMotionController;
import org.debux.webmotion.server.render.Render;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;

public class Item extends WebMotionController {
	public Render getById(Long id) throws ApiException {
		System.out.println("id:" + id);
		TaobaoClient client = new DefaultTaobaoClient(APP_URL, APP_KEY,
				APP_SECRET);
		ItemGetRequest req = new ItemGetRequest();
		req.setFields("num_iid,title,nick,cid,pic_url,num,list_time,delist_time,price,modified,approve_status");
		req.setNumIid(id);
		ItemGetResponse response = client.execute(req, SESSION_KEY);
		handleRep(response);
		com.taobao.api.domain.Item item = response.getItem();
		System.out.println(item.getTitle());
		return renderView("getitem.jsp", "item", item);
	}



	public Render getOnSale() throws ApiException {
		TaobaoClient client = new DefaultTaobaoClient(APP_URL, APP_KEY,
				APP_SECRET);
		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		req.setFields("approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id");
		req.setPageSize(100L);
		long pageNo = 0;
		long max = 1L;
		LinkedList<com.taobao.api.domain.Item> items=new LinkedList<com.taobao.api.domain.Item>();
		do {
			req.setPageNo(pageNo++);
			ItemsOnsaleGetResponse response = client.execute(req, SESSION_KEY);
			if (handleRep(response)) {
				break;
			}
			max = response.getTotalResults();
			items.addAll(response.getItems());
		} while (100 * pageNo < max);
		return renderView("getitem.jsp", "items", items);
	}
	private boolean handleRep(TaobaoResponse response) {
		boolean b=!response.isSuccess();
		if (b) {
			System.out.println(response.getMsg());
			System.out.println(response.getErrorCode());
			System.out.println(response.getSubCode());
			System.out.println(response.getSubMsg());
		}
		return b;
	}
}
